library ieee;
use ieee.std_logic_1164.all;
use ieee.std_logic_unsigned.all;

entity irqcu is
	generic
	(
		DATA_WIDTH	: natural  :=	32
	);

	port
	(
		-- Input ports
		irq_0	: in std_logic;
		irq_1	: in std_logic;
		irq_2	: in std_logic;
		irq_3	: in std_logic;
		clock	: in std_logic;
		iret	: in std_logic;
		jpatch	: in std_logic;
		pc	: in std_logic_vector(DATA_WIDTH-1 downto 0);
		
		-- Output ports
		irqaddr	: out std_logic_vector(DATA_WIDTH-1 downto 0);
		irq	: out std_logic;
		rtn	: out std_logic
	);
end irqcu;

architecture rtl_irqcu of irqcu is
shared variable irq0,irq1,irq2,irq3: std_logic;
shared variable retaddr : std_logic_vector(DATA_WIDTH-1 downto 0);
shared variable irqmark : std_logic:= '0';
begin
	process (clock)
	begin
		if clock'EVENT and clock = '1' then
			irq0 := irq0 or irq_0;
			irq1 := irq1 or irq_1;
			irq2 := irq2 or irq_2;
			irq3 := irq3 or irq_3;			
			
			if (irq_0 = '1' or irq_1 = '1' or irq_2 = '1' or irq_3 = '1' or
				irq0 = '1' or irq1 = '1' or irq2 = '1' or irq3 = '1') and (irqmark = '0') then
				irq <= '1';
				rtn <= '0';
				if (iret = '0') then
					retaddr := pc;
				end if;
				irqmark := '1';
				if (irq_0 = '1') then
					--irqaddr <= X"00000080";
					irqaddr <= X"80000000";
					irq0 := '0';
				elsif (irq_1 = '1') then
					--irqaddr <= X"00000088";
					irqaddr <= X"80000008";
					irq1 := '0';
				elsif (irq_2 = '1') then
					--irqaddr <= X"00000090";
					irqaddr <= X"80000010";
					irq2 := '0';
				elsif (irq_3 = '1') then
					--irqaddr <= X"00000098";
					irqaddr <= X"80000018";
					irq3 := '0';
				end if;
			else
				irq <= '0';
			end if;
			if (iret = '1') then				
				if (irq0 = '1' or irq1 = '1' or irq2 = '1' or irq3 = '1') then
					irq <= '1';
					rtn <= '0';
					if (irq0 = '1') then
						--irqaddr <= X"00000080";
						irqaddr <= X"80000000";					
						irq0 := '0';
					elsif (irq1 = '1') then
						--irqaddr <= X"00000088";
						irqaddr <= X"80000008";
						irq1 := '0';
					elsif (irq2 = '1') then
						--irqaddr <= X"00000090";
						irqaddr <= X"80000010";
						irq2 := '0';
					elsif (irq3 = '1') then
						--irqaddr <= X"00000098";
						irqaddr <= X"80000018";
						irq3 := '0';
					end if;
				else
					rtn <= '1';
					irqaddr <= retaddr;
					irqmark := '0';
				end if;	
			else
				rtn <= '0';
			end if;
			if (jpatch = '1') then
				retaddr := retaddr-4;
			end if;
		end if;
	end process;
end rtl_irqcu;

